#include <webx/route.h>
#include <dbentity/T_XG_CGI.h>

class EditCgi : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(EditCgi)

int EditCgi::process()
{
	param_int(port);
	param_string(host);

	param_int(maxsz);
	param_int(maxcnt);
	param_int(enabled);
	param_string(path);
	param_string(flag);
	param_string(remark);
	param_int(hostmaxcnt);

	webx::CheckSystemRight(this);

	if (host.length() > 0)
	{
		HttpRequest request(this->request->getPath());

		request.setHeadHost(host, port);
		request.setParameter("path", path);
		request.setParameter("flag", flag);
		request.setParameter("maxsz", maxsz);
		request.setParameter("maxcnt", maxcnt);
		request.setParameter("remark", remark);
		request.setParameter("enabled", enabled);
		request.setParameter("hostmaxcnt", hostmaxcnt);

		SmartBuffer data = request.getResult(host, port);

		if (data.isNull()) return simpleResponse(XG_ERROR);

		out << data.str();

		return XG_OK;
	}

	path = CgiMapData::GetKey(path);

	if (path.empty() || enabled < CGI_DISABLE || enabled > CGI_PUBLIC) return simpleResponse(XG_PARAMERR);

	int res = 0;
	CT_XG_CGI tab;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	tab.init(dbconn);

	tab.path = path;
	tab.maxsz = maxsz;
	tab.maxcnt = maxcnt;
	tab.remark = remark;
	tab.enabled = enabled;
	tab.statetime.update();
	tab.hostmaxcnt = hostmaxcnt;

	if (flag == "D")
	{
		res = tab.remove();

		if (res >= 0) app->removeCgiAccess(path);
	}
	else if (flag == "U")
	{
		res = tab.insert();

		if (res < 0) res = tab.update();
	}
	else
	{
		res = XG_PARAMERR;
	}

	if (res >= 0) app->updateCgiData(path);

	json["code"] = res;
	out << json;
	
	return XG_OK;
}